package com.lwl.inter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Lei
 * @create 2022-10-16 11:33
 */

public class LoginIntercaptor implements HandlerInterceptor {
//    如果没有拦截器，那么需要在每个方法里面都写上对应的判断语句，去判断session中是否有值
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginUsername");
//        System.out.println("userXXXXXXXXXXXXXXXXX = " + user);
        if (user==null){
//            如果session中没有值，那么就进行重定向，因为不知道是几层路径，所以这里重定向选择的是绝对路径：项目名称/路径
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/login.jsp");
            return false;
        }else {
//            如果有值，那么就走下一个过滤器
            return true;
        }

    }
//此方法在Controller的业务方法执行之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
//此方法在Controller的业务方法执行结束并且视图解析完成后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
